import fs from 'fs'

import PROJECT from './PROJECT'

const name = process.env.MODE_ENV || 'development'
const MODE_TEST = process.env.MODE_TEST === 'true'
const MODE_SSR = name === 'hot' ? false : process.env.MODE_SSR === 'true'

const parseENV = () => {
  let str = ''
  try {
    str = fs.readFileSync(PROJECT.SRC.ENV)
  } catch (e) {
    console.log('[PROMPT] ENV.json file not found, use the default ENV config')
    return {}
  }
  return JSON.parse(str)
}

const ENV_NEW = parseENV()

const hot = {
  NAME: 'hot',
  HOST: '0.0.0.0',
  PORT: 3000,
  IS_MOBILE: false,
  IS_NEED_ANALYZER: false,
  IS_SIMPLE: false,
  IS_DEV: true,
  IS_CLIENT: false,
  PUBLIC: '/',
}

const development = {
  NAME: 'development',
  HOST: 'localhost',
  PORT: 3000,
  IS_MOBILE: false,
  IS_NEED_ANALYZER: false,
  IS_SIMPLE: false,
  IS_DEV: true,
  IS_CLIENT: false,
  PUBLIC: '/static-dev/',
}

const test = {
  NAME: 'test',
  HOST: '0.0.0.0',
  PORT: 80,
  IS_MOBILE: false,
  IS_NEED_ANALYZER: false,
  IS_SIMPLE: false,
  IS_DEV: false,
  IS_CLIENT: false,
  PUBLIC: '/static-test/',
}

const production = {
  NAME: 'production',
  HOST: '0.0.0.0',
  PORT: 80,
  IS_MOBILE: false,
  IS_NEED_ANALYZER: false,
  IS_SIMPLE: false,
  IS_DEV: false,
  IS_CLIENT: false,
  PUBLIC: '/static/',
}

const ENV = {
  hot,
  development,
  test,
  production,
}

if (!ENV[name]) {
  throw new Error(`the env "${name}" is invalid, use one in (${Object.keys(ENV)})`)
}

const env = ENV[name]
const common = ENV_NEW.common
const envNew = ENV_NEW[name]
const lock = {
  MODE_TEST,
  MODE_SSR,
  NAME: env.NAME,
  IS_DEV: env.IS_DEV,
  IS_CLIENT: env.IS_CLIENT,
}

Object.assign(
  env,
  common,
  envNew,
  lock,
)

for (const k in env) {
  const t = typeof env[k]
  if (t !== 'string' && t !== 'number' && t !== 'boolean') {
    throw new Error(`the key "${k}" in enviroment "${name}" should not be the type out of { number, string, boolean }`)
  }
}

export {
  env as ENV,
  ENV_NEW as ENVS,
}
